package com.xxx.user.mq;

import com.xxx.user.service.OrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@AllArgsConstructor
@RocketMQTransactionListener
public class TransactionMsgListener implements RocketMQLocalTransactionListener {

    private final OrderService orderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        int i = 1 / 0; //触发回查
        try {
            String jsonString = new String((byte[]) message.getPayload());
            String key = message.getHeaders().get("key").toString();
            String messageType = message.getHeaders().get("type").toString();

            switch (messageType) {
                case "order_create":
                    log.info("order_create 消息");
                case "order_cancel":
                    log.info("order_cancel 消息");
                default:
                    log.info("default 消息");
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String key = Objects.requireNonNull(message.getHeaders().get("key")).toString();
        String messageType = Objects.requireNonNull(message.getHeaders().get("type")).toString();
        try {
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}